package com.mw.mwreaderdemo;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class AT102 extends Activity {

	private Button btnReadErrCounter;
	private Button btnCheckPwd;
	private Button btnReadPwd;
	private Button btnChangePwd;
	private Button btnReadData;
	private Button btnReadDataloop;
	private Button btnWriteData;
	private Button btnSP;
	private Button btnCancelSP;
	private Button btnPersonalized;
	private Button btnReadProtClear;
	private Button btnWriteProtClear;

	private Spinner spPwdType;
	private Spinner spApplication;

	private EditText etPassword;
	private EditText etData;
	private EditText etOffset;
	private EditText etLen;
	private EditText etResult;
	private Thread mIdCardThread;

	//  上一次点击的时间 long型  
	private long beforeClick = 0;
	private String TAG = "AT102";
	private int pwdType = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_at102);

		btnReadErrCounter = (Button) findViewById(R.id.btnReadErrCounter);
		btnCheckPwd = (Button) findViewById(R.id.btnCheckPwd);
		btnReadPwd = (Button) findViewById(R.id.btnReadPwd);
		btnChangePwd = (Button) findViewById(R.id.btnChangePwd);
		btnReadData = (Button) findViewById(R.id.btnReadData);
		btnReadDataloop = (Button) findViewById(R.id.btnReadDataloop);
		btnWriteData = (Button) findViewById(R.id.btnWriteData);
		btnSP = (Button) findViewById(R.id.btnSP);
		btnCancelSP = (Button) findViewById(R.id.btnCancelSP);
		btnPersonalized = (Button) findViewById(R.id.btnPersonalized);
		btnReadProtClear = (Button) findViewById(R.id.btnReadProtClear);
		btnWriteProtClear = (Button) findViewById(R.id.btnWriteProtClear);

		spPwdType = (Spinner) findViewById(R.id.spPwdType);
		spApplication = (Spinner) findViewById(R.id.spApplication);

		etPassword = (EditText) findViewById(R.id.etPassword);
		etData = (EditText) findViewById(R.id.etData);
		etOffset = (EditText) findViewById(R.id.etOffset);
		etLen = (EditText) findViewById(R.id.etLen);
		etResult = (EditText) findViewById(R.id.etResult);

		// 设置输入字符转换为大写
		etPassword.setTransformationMethod(new InputLowerToUpper());
		etData.setTransformationMethod(new InputLowerToUpper());

		// 设置双击操作信息提示框清除数据
		etResult.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View arg0, MotionEvent event) {
				// TODO Auto-generated method stub
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					if (System.currentTimeMillis() - beforeClick > 500) {
						beforeClick = System.currentTimeMillis();
					} else {
						etResult.setText("");
					}
				}
				return false;
			}
		});

		spPwdType.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				// TODO Auto-generated method stub
				if (position == 0) {
					etPassword.setFilters(new InputFilter[] { new InputFilter.LengthFilter(4) });
				} else if (position == 1) {
					etPassword.setFilters(new InputFilter[] { new InputFilter.LengthFilter(12) });
				} else if (position == 2) {
					etPassword.setFilters(new InputFilter[] { new InputFilter.LengthFilter(8) });
				}
				pwdType = position;
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub

			}
		});

		btnReadErrCounter.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (MainActivity.reader == null) {
					Toast.makeText(AT102.this, "设备未打开", Toast.LENGTH_SHORT).show();
					return;
				}

				try {
					etResultAddStr("用户密码错误计数为: " + MainActivity.reader.readErrorCount102());
					etResultAddStr("应用2区擦除密码错误计数为: " + MainActivity.reader.readEraseCount102());
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					etResultAddStr(e.getMessage());
				}
			}
		});

		btnCheckPwd.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (MainActivity.reader == null) {
					Toast.makeText(AT102.this, "设备未打开", Toast.LENGTH_SHORT).show();
					return;
				}

				try {
					MainActivity.reader.verifyPassword102(pwdType, etPassword.getText().toString());
					etResultAddStr("校验密码成功!");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					etResultAddStr(e.getMessage());
				}
			}
		});

		btnReadPwd.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (MainActivity.reader == null) {
					Toast.makeText(AT102.this, "设备未打开", Toast.LENGTH_SHORT).show();
					return;
				}

				try {
					etResultAddStr(MainActivity.reader.readPassword102(pwdType));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					etResultAddStr(e.getMessage());
				}
			}
		});

		btnChangePwd.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (MainActivity.reader == null) {
					Toast.makeText(AT102.this, "设备未打开", Toast.LENGTH_SHORT).show();
					return;
				}

				try {
					MainActivity.reader.changePassword102(pwdType, etPassword.getText().toString());
					etResultAddStr("更改密码成功!");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					etResultAddStr(e.getMessage());
				}
			}
		});
		
		//读卡
		btnReadData.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (MainActivity.reader == null) {
					Toast.makeText(AT102.this, "设备未打开", Toast.LENGTH_SHORT).show();
					return;
				}

				int offset = Integer.parseInt(etOffset.getText().toString());
				int length = Integer.parseInt(etLen.getText().toString());
				try {
					etResultAddStr(MainActivity.reader.read102(offset, length));

					//Log.i("mwcard", "读24c: begin");					
					//etResultAddStr(MainActivity.reader.read24CXX(5, 0, 128));
					//Log.i("mwcard", "读24c: end");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					etResultAddStr(e.getMessage());
				}
			}
		});
		
		//循环读卡
		btnReadDataloop.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub			
				mIdCardThread = new Thread() {
		            @Override
		            public void run() { 
		            	onIdCardThreadRun(); 
		            }
		        };
		        mIdCardThread.start();
			}
		});
		
		btnWriteData.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (MainActivity.reader == null) {
					Toast.makeText(AT102.this, "设备未打开", Toast.LENGTH_SHORT).show();
					return;
				}

				int offset = Integer.parseInt(etOffset.getText().toString());
				String str = etData.getText().toString();
				int len = str.length() / 2;
				try {
					// 先擦除
					MainActivity.reader.erase102(offset, len);
					MainActivity.reader.write102(offset, str);								
					etResultAddStr("写数据成功!");
										
					//Log.i("mwcard", "写24c: 偏移量offset："+offset);
					//Log.i("mwcard", "写24c: 数据str："+str);					
					//Log.i("mwcard", "写24c: begin");
					//MainActivity.reader.write24CXX(5, offset, str);
					//Log.i("mwcard", "写24c: end");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					etResultAddStr(e.getMessage());
				}
			}
		});

		btnSP.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (MainActivity.reader == null) {
					Toast.makeText(AT102.this, "设备未打开", Toast.LENGTH_SHORT).show();
					return;
				}

				try {
					MainActivity.reader.simulationPersonalization102(1);
					etResultAddStr("模拟个人化成功");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					etResultAddStr(e.getMessage());
				}
			}
		});

		btnCancelSP.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (MainActivity.reader == null) {
					Toast.makeText(AT102.this, "设备未打开", Toast.LENGTH_SHORT).show();
					return;
				}

				try {
					MainActivity.reader.simulationPersonalization102(0);
					etResultAddStr("取消模拟个人化成功");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					etResultAddStr(e.getMessage());
				}
			}
		});

		btnPersonalized.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (MainActivity.reader == null) {
					Toast.makeText(AT102.this, "设备未打开", Toast.LENGTH_SHORT).show();
					return;
				}

				try {
					MainActivity.reader.personalization102();
					etResultAddStr("个人化成功");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					etResultAddStr(e.getMessage());
				}
			}
		});

		btnReadProtClear.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (MainActivity.reader == null) {
					Toast.makeText(AT102.this, "设备未打开", Toast.LENGTH_SHORT).show();
					return;
				}

				try {
					int sector = spApplication.getSelectedItemPosition() + 1;
					MainActivity.reader.initReadControl102(sector);
					etResultAddStr("读保护位清0成功");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					etResultAddStr(e.getMessage());
				}
			}
		});

		btnWriteProtClear.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (MainActivity.reader == null) {
					Toast.makeText(AT102.this, "设备未打开", Toast.LENGTH_SHORT).show();
					return;
				}

				try {
					int sector = spApplication.getSelectedItemPosition() + 1;
					MainActivity.reader.initWriteControl102(sector);
					etResultAddStr("写保护位清0成功");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					etResultAddStr(e.getMessage());
				}
			}
		});

	}
	
	private static final int MSG_ReadCardSuccess = 0;
	private static final int MSG_ReadCardFailes = 1;
	private static final int MSG_Compare = 2;
	private static final int socket_conn = 3;
	private static final int socket_send = 4;
	public String mNum;
	public int iNum = 0;
	private volatile boolean mIdCardThreadRun;
    private void onIdCardThreadRun() { 
    	mIdCardThreadRun = true;
        while (mIdCardThreadRun) {     	
        	try 
        	{		
				int offset = Integer.parseInt(etOffset.getText().toString());
				int length = Integer.parseInt(etLen.getText().toString());				
				mNum = MainActivity.reader.read102(offset, length);				
				Thread.sleep(100);
        		//MainActivity.reader.beep(1,2,1);
				handler.sendEmptyMessage(MSG_Compare);
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();			
			}         			
        } 
    }
	
    private Handler handler = new Handler()
    {
	   public void handleMessage(Message msg)
	   {
		   super.handleMessage(msg);
		   switch (msg.what)
		   {
				case MSG_ReadCardSuccess:		

					break;					
				case MSG_ReadCardFailes:
					etResultAddStr("102卡数据"+iNum+": " + "设备未打开");	
					iNum ++;
					break;
					
				case MSG_Compare:					
					etResultAddStr("102卡数据"+iNum+": " + mNum);	
					iNum ++;
					break;
				case socket_conn:
					
					break;			
				case socket_send: //socket发送
					
					break;
				default:
					break;
		   }
	   }
   };   
	
	/**
	 * @Description 提示信息框添加信息
	 * @param str
	 *            要添加的信息
	 * @return void
	 */
	private void etResultAddStr(String str) {
		if(etResult.getLineCount() > 1000) //超过1000行，删除一次
		{
			etResult.setText("");
		}
		int index = etResult.getSelectionStart();
	    Editable editable = etResult.getText();
	    editable.insert(index, str+ "\n");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.at102, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
